;
(function() {
  var ACCOUNTID = hlUrlUtil.GetQueryString('id'); //账单id
  var CONTRACTID = hlUrlUtil.GetQueryString('aid'); //合同id
  var PAGE = hlUrlUtil.GetQueryString('page'); //合同id
  var permissions = window.localStorage.getItem('permissions') //page

  Array.prototype.removeRepeatBuildingAndFLoor = function() {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  new Vue({
    el: '#carryOver',
    data: {
      idA: {
        ida: ACCOUNTID,
        idb: CONTRACTID
      },
      contractData: {
        ot: [],
        st: []
      },
      billData: {
        expenses: [],
        transactions: [],
        invoiceInfos: []
      },
      permissions: JSON.parse(permissions),
      pageAs: PAGE,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: false,
      wpOpenFlag: false,
      stOpenFlag: false,
      isEditCountMes: false,

			// 20190522
			page: 1,
			keyword: '',
			isCarryOverDisplay: false,
			targetExpenseArr: [],
			targetExpenseSelect: {name: '', amountTPay: '', id: ''},
			sourceExpenseArr: [],
			sourceExpenseSelect: [],
			sourceExpenseExpenseIds: [],
			sourceExpenseDisplaySelect: [],
			rentUnits: [],
			lefthover: 0,
			tophover: 0,
			texthover: false,
			textLong: '',
    },
    filters: {
      timestamp: function(time) {
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      billState: function(state) {
        if (!state) return '';
        return hlCodeConvert.billPaymentState(state)
      },
      toFixed2: function(n) {
        return Number(n).toFixed(2)
      },
      billPayWay: function(state) {
        return hlCodeConvert.billPayWay(state)
      },
			//绝对值
			absNumber (item) {
				return Math.abs(item)
			},
      //千分位
      formatNum: function(n) {
        return hlNumberUtil.formatNum(n)
      },
      absNum: function(n) {
        return Math.abs(n)
      }
    },
		computed: {
			totalAmountTpay () {
				let res = 0;
				this.sourceExpenseDisplaySelect.map(item => {
					if ( item.carry_over_amount ) {
						res += Number(item.carry_over_amount)
					}
				})
				return res
			}
		},
    methods: {
			//显示hover
			hoverText(e, data) {
				if (!data) return;
				if (!data.length) return;
				this.texthover = true;
				this.rentUnits = data;
				var l = e.srcElement.offsetLeft;
				var t = e.srcElement.parentNode.offsetTop + 40
				this.lefthover = l + 'px';
				this.tophover = t + 'px';
			  setTimeout(() => {
					var s = this.$refs.widthCal ? this.$refs.widthCal.offsetWidth/2 : 1;
					l = l-s+(e.srcElement.offsetWidth/2);
					this.lefthover = l + 'px';
					this.tophover = t + 'px';
				}, 30)
			},
			mouseleaveOut() {
			  this.lefthover = 0 + 'px';
			  this.tophover = 0 + 'px';
			  this.textLong = [];
				this.texthover = false;
			},

      // 获取合同单元信息
      getContractUnitsData: function() {
        var self = this;
        hlhttp.get({
          url: 'contract/units',
          data: {
            id: CONTRACTID
          },
          success: function(data) {
            // 单元
            var buildingData = self.dealWithUnitData(data)
            self.totalArea = buildingData.totalArea
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.map(function(item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      // 单元数据去重整合处理
      dealWithUnitData: function(unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function(_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 查看出租资源详情信息
      checkDetailMes: function(type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      //获取合同信息
      getContractData: function() {
        var _this = this;
        contract.formatUnitData(CONTRACTID, function(data) {
          _this.contractData = data
        })
      },

      //获取意向详情
      getYxInfo(id) {
        var self = this;
        hlhttp.get({
          url: 'contract/intent',
          data: {
            id: id
          },
          success: (data) => {
            data.projectInfo.units.map(item => {
              item.positions = [];
              item.floorName = item.floorNum
            })
            this.contractData.zlfCompany = data.zlfInfo.zlfName
            this.contractData.projectName = data.projectInfo.projectName
            var buildingData = this.dealWithUnitData(data.projectInfo.units)
            this.totalArea = buildingData.totalArea
            this.building = buildingData.building;
            this.printflag = false;
            // this.billData.billTypeName = data.intentTypeVal;
            this.st = [];
            this.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            //车位
            let newStArr = hlArrayUtil.removeRepeat(data.projectInfo.stops, 'unitId'),
              newStIds = [];
            newStArr.map(item => {
              item.floor = item.floorNum;
              item.floorName = item.floorNum
              item.positions = []
            })
            data.projectInfo.stops.map(item => {
              newStIds.push(item.stopId)
              newStArr.map(item1 => {
                if (item.unitId == item1.unitId) {
                  stTotalNum++
                  item1.positions.push({
                    positionName: item.stopName,
                    positionId: item.stopId
                  })
                }
              })
            })
            self.st = newStArr;
            let newWpArr = hlArrayUtil.removeRepeat(data.projectInfo.wps, 'unitId'),
              newWpIds = [];
            newWpArr.map(item => {
              item.floor = item.floorNum
              item.positions = []
            })
            data.projectInfo.wps.map(item => {
              newWpIds.push(item.wpId)
              newWpArr.map(item1 => {
                if (item.unitId == item1.unitId) {
                  wpTotalNum++
                  item1.positions.push({
                    positionName: item.wpName,
                    positionId: item.wpId
                  })
                }
              })
            })
            this.wp = newWpArr
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      //获取账单信息
      getBillData: function() {
        var _this = this;
        hlhttp.get({
          url: 'bill,expenses,transactions',
          data: {
            bill_id: ACCOUNTID
          },
          success: function(data) {
            if (data.intentId) {
              _this.getYxInfo(data.intentId)
            }
            CONTRACTID = data.contractId
            if (CONTRACTID) {
              _this.getContractData()
            }

						// ************ 营业额本次新增逻辑 start **********
						let amountReceivedRent = 0;  //固定租金金额
						let commissioAmount = 0;  //营业额金额
						let IsCompareRentAmtFlag = false; //判断是否是取其高
						data.expenses.map(item => {
							item.flag = true;
							item.styleFlag = false;
							if (item.expenseType == 'R') {
								amountReceivedRent = item.amountReceived;
							}
							if (item.expenseType == 'CM') {
								commissioAmount = item.amountReceived;
							}
						})
						if (data.compareRentAmtFlag && data.commissonConfirmFlag && data.commissionFlag) {
							if (data.compareRentAmtFlag == 'Y' && data.commissionFlag == 'Y' && data.commissonConfirmFlag == 'Y') {
								IsCompareRentAmtFlag = true;
							}
						}
						if (data.compareRentAmtFlag && data.commissonConfirmFlag && data.commissionFlag) {
							if (data.compareRentAmtFlag == 'N' && data.commissionFlag == 'Y' && data.commissonConfirmFlag == 'N') {
								data.expenses.map(item => {
									if (item.expenseType == 'CM') {
										item.flag = false;
									}
									if (item.expenseType == 'R') {
										item.flag = false;
									}
								})
							}
						}
						if (data.compareRentAmtFlag && data.commissonConfirmFlag && data.commissionFlag) {
							if (data.compareRentAmtFlag == 'Y' && data.commissonConfirmFlag == 'N' && data.commissionFlag == 'Y') {
								data.expenses.map(item => {
									if (item.expenseType == 'CM') {
										item.flag = false;
										item.styleFlag = false;
									}
									if (item.expenseType == 'R') {
										item.flag = false;
										item.styleFlag = false;
									}
								})
							}
						}
						if (IsCompareRentAmtFlag) {
							data.expenses.map(item => {
								if (item.expenseType == 'CM') {
									if (item.amountReceived <= amountReceivedRent) {
										item.flag = false;
										item.styleFlag = true;
									}
								}
								if (item.expenseType == 'R') {
									if (item.amountReceived <= commissioAmount) {
										item.flag = false;
										item.styleFlag = true;
									}
								}
							})
						}
						// ************ 营业额本次新增逻辑 end *************

            _this.billData = data;

            _this.receiptDeadlineDate = hlDateUtil.formatUTCDate(data.deadlineDate, 'yyyy-MM-dd')
          }
        })
      },

			// 20190522 start
			addCarryOver () {
				this.isCarryOverDisplay = true;
				this.synchronizationData()
				this.sourceExpense()
			},
			// 新增结转-结转目标费项
			targetExpense () {
				hlhttp.get({
					url: 'bill/target_expense/_search',
					data: {bill_id: ACCOUNTID},
					success: (data) => {
						console.log(data)
						this.targetExpenseArr = data;
					}
				})
			},
			//选择结转费项
			selectCarryOverExpense (item) {
				this.targetExpenseSelect = {name: item.name, amountTPay: item.amountTPay, id: item.id, expenditureId: item.expenditureId}
				this.sourceExpenseDisplaySelect = []
			},
			//新增结转-选择费项页
			sourceExpense () {
				hlhttp.get({
					url: 'bill/source_expense/_search',
					data: {
						bill_id: ACCOUNTID,
						carry_over_flag: this.targetExpenseSelect.amountTPay > 0 ? 'Y' : 'N',
						customer_name: this.keyword || '#',
						page: this.page,
						limit: 7
					},
					success: (data) => {
						console.log(data)
						this.sourceExpenseArr = data.sourceExpenses;
						$("#page").initPage(data.totalPage, this.page, (n) => {
						  if (this.page == n) {
						    return
						  }
						  this.page = n;
						  this.sourceExpense();
						});
					}
				})
			},
			//选择费项
			selectExpense (item) {
				if (this.sourceExpenseExpenseIds.indexOf(item.id) == -1) {
					this.sourceExpenseExpenseIds.push(item.id)
					this.sourceExpenseSelect.push({
						"project_id": item.projectId,
						"contract_id": item.contractId,
						"target_bill_id": ACCOUNTID,
						"target_expense_id": this.targetExpenseSelect.id,
						"target_expense_name": this.targetExpenseSelect.name,
						"target_bill_no": this.billData.no,
						"source_bill_id": item.billId,
						"source_expense_id": item.id,
						"source_expense_name": item.name,
						"source_bill_no": item.billNo,
						"amount": item.amountTpay,
						"source_expense_state": item.sourceExpenseState,
						"target_expense_state": this.targetExpenseSelect.amountTPay > 0 ? 'Y' : 'N',
						"carry_over_amount": item.carry_over_amount || '',
						"carry_over_date": item.carry_over_date || '',
						"memo": item.memo || '',
						"source_expense_amountTpay": item.amountTpay,
						"target_expenditure_id": this.targetExpenseSelect.expenditureId || '#',
						"source_expenditure_id": item.expenditureId || '#'
					})
				} else {
					this.sourceExpenseExpenseIds.splice(this.sourceExpenseExpenseIds.indexOf(item.id), 1)
					this.sourceExpenseSelect.splice(this.sourceExpenseExpenseIds.indexOf(item.id), 1)
				}
			},
			//确认选择当前费项列表
			queryExpense () {
				this.sourceExpenseDisplaySelect = JSON.parse(JSON.stringify(this.sourceExpenseSelect))
				this.isCarryOverDisplay = false;
			},
			//取消选择费项列表
			cancelExpense () {
				this.isCarryOverDisplay = false;
				this.synchronizationData()
			},
			//同步选择数据
			synchronizationData () {
				this.sourceExpenseExpenseIds = []
				if (!this.sourceExpenseDisplaySelect.length) {
					this.sourceExpenseSelect = []
					return
				}
				this.sourceExpenseSelect = JSON.parse(JSON.stringify(this.sourceExpenseDisplaySelect))
				this.sourceExpenseDisplaySelect.map(item => {
					this.sourceExpenseExpenseIds.push(item.source_expense_id)
				})
			},
			//删除某个结转
			delCarryOver (i) {
				this.sourceExpenseDisplaySelect.splice(i, 1)
			},
			//选择某个结转时间验证
			validateTime (i) {
				let nowTime = new Date().getTime();
				let selectTime = new Date(this.sourceExpenseDisplaySelect[i].carry_over_date).getTime();
				setTimeout(() => {
					if (selectTime > nowTime) {
						this.sourceExpenseDisplaySelect[i].carry_over_date = '';
						hl.toast('所选日期不能超出当前日期')
					}
				}, 30)
			},
			//结转金额验证
			validateAmount (i) {
				if (isNaN(this.sourceExpenseDisplaySelect[i].carry_over_amount)) return
				if (Number(this.sourceExpenseDisplaySelect[i].carry_over_amount) <= 0) {
					hl.toast('结转金额需为正数')
					this.sourceExpenseDisplaySelect[i].carry_over_amount = '';
					return
				}
				setTimeout(() => {
					let now = Number(this.sourceExpenseDisplaySelect[i].carry_over_amount);
					let that = Number(this.sourceExpenseDisplaySelect[i].amount)
					if ( Math.abs(now) > Math.abs(that)) {
						this.sourceExpenseDisplaySelect[i].carry_over_amount = '';
						hl.toast('结转金额不能大于可结转金额')
					}
				}, 30)
			},
			//确认结转验证
			queryValidate () {
				let flag = true;
				for (let i = 0; i < this.sourceExpenseDisplaySelect.length; i++) {
					let item = this.sourceExpenseDisplaySelect[i];
					if (!item.carry_over_amount) {
						hl.toast('结转' + (i+1) + ' 结转金额不能为空')
						flag = false;
						break;
					}
					if (!item.carry_over_date) {
						hl.toast('结转' + (i+1) + ' 结转时间不能为空')
						flag = false;
						break;
					}
				}
				if (Math.abs(this.targetExpenseSelect.amountTPay) < Number(this.totalAmountTpay)) {
					flag = false
					hl.toast('此次结转金额不能大于待结转金额')
				}
				return flag
			},
			querySubmit () {
				if (!this.queryValidate()) return;
				let data = JSON.parse(JSON.stringify(this.sourceExpenseDisplaySelect))
				for (let i = 0; i < data.length; i++) {
					let item = data[i];
					for (let key in item) {
						data[i][key] = data[i][key] ? data[i][key] : '#'
					}
				}

				if (!this.targetExpenseSelect.name) {
					hl.toast('请选择未结清待结转费项')
					return
				}
				if (!data.length) {
					hl.toast('请新增结转来源费项')
					return
				}

				hlhttp.post({
					url: 'bill/carry_over_info/_batch',
					data: {
						bill_id: ACCOUNTID,
						carry_over_infos: JSON.stringify(data)
					},
					success: (data) => {
						hlUrlUtil.goTo('billDetail', {id: ACCOUNTID, aid: CONTRACTID, ddtab: true, page: this.page}, false)
					}
				})
			},
			//结转费项查询
			carryOverSearch () {
				this.page = 1;
				this.sourceExpense()
			},
			//结转费项重置
			carryOverReset () {
				this.page = 1;
				this.keyword = ''
				this.sourceExpense()
			},
    },
    mounted: function() {
      this.getContractUnitsData()
      this.getBillData()
			this.targetExpense()
			hlSelectUi()
    }
  })
}())
